from django.shortcuts import render
from rest_framework.generics import ListAPIView
from django.contrib.auth.models import User
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django_redis import get_redis_connection
# 对日志调用
import logging

import Constants
from models import CacheView
from .models import Nav, Category, Banner
from .serializers import NavModelSerializer, CategorySerializer, BannerModelSerializer

logger = logging.getLogger("django")

# Create your views here.
class HomeAPIView(APIView):
    def get(self,request):

        """测试代码，测试完成以后将来可以删除"""
        # 测试日志功能
        # logger.error("error信息")
        # logger.info("info信息")
        redis = get_redis_connection("sms_code")
        brother = redis.lrange("brother", 0, -1)
        return Response(brother, status.HTTP_200_OK)

# 处理前端的请求
# 获取顶部导航栏数据
class NavHeaderListApiView(CacheView):
    queryset = Nav.objects.filter(is_show=True,is_deleted=False,position=Constants.NAV_HEADER).order_by("orders")[:Constants.NAV_HEADER_SIZE]
    serializer_class = NavModelSerializer

# 获取底部导航栏数据
class NavFooterListApiView(CacheView):
    queryset = Nav.objects.filter(is_show=True,is_deleted=False,position=Constants.NAV_FOOTER).order_by("orders")[:Constants.NAV_FOOTER_SIZE]
    serializer_class = NavModelSerializer

# 获取首页分类的数据
class CategoryListApiView(APIView):
    def get(self,request):
        all=Category.objects.filter(parent=None,is_show=True,is_deleted=False,ishome=True).order_by("orders")
        for i in all:
            print(i)
        ser=CategorySerializer(all,many=True)
        return Response({'msg':"ok","data":ser.data,"code":200})
# class CategoryListApiView(ListAPIView):
#     queryset = Category.objects.filter(is_show=True,is_deleted=False,ishome=True).order_by("orders")
#     serializer_class = CategorySerializer(queryset,many=True)

# 获取分类的详情信息
class CategoryDetailViews(APIView):
    def get(self,request):
        # 1.获取一级分类的id
        cid=request.GET.get("id")
        # 2.根据一级分类的id,查找列表(主键查询)
        info=Category.objects.filter(id=cid,is_show=True,is_deleted=False,ishome=True,parent=None).first()
        ser=CategorySerializer(info)
        return Response({"msg":"ok","data":ser.data,"code":200})

# 轮播图
class  BannerListApiView(CacheView):
    queryset = Banner.objects.filter(is_show=True,is_deleted=False).order_by("orders")[:5]
    serializer_class = BannerModelSerializer


# class  BannerListApiView(APIView):
#     def get(self,request):
#         #获取视图列表
#         all=Banner.objects.filter(is_show=True,is_deleted=False).order_b y("orders")[:5]
#         ser=BannerModelSerializer(all)
#         return  Response({"msg":"ok","data":ser.data,"code":200})

